const cloud = require('wx-server-sdk');

cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
});

const db = cloud.database()

// 获取openId云函数入口函数
exports.main = async (event, context) => {
  // 获取基础信息
  const wxContext = cloud.getWXContext();
  const openid = wxContext.OPENID;
  const _avatarUrl = event._avatarUrl;
  const _phone = event._phone;
  const _nickName = event._nickName;
  const action = event.action;
  try {
    // 查询云数据库中是否存在该 openid 对应的数据
    const res = await db.collection('users').where({
      _openid: openid
    }).get()
    let userInfoRes = {}
    if (res.data.length > 0) {
      const { _openid, ...rest } = res.data[0];
      userInfoRes = rest;
    }
    else if(action == "login"){
      return {
        code: 201,
        msg: "请先注册！"
      }
    } 
    else {
      // 保存到数据库
      const saveRes = await db.collection('users').add({
        data: {
            _openid: openid,
            _avatarUrl: _avatarUrl,
            _nickName: _nickName,
            _phone: _phone,
            _createTime: db.serverDate()
        }
      });
      userInfoRes = {
        "_id": saveRes._id,
        "_avatarUrl": _avatarUrl,
        "_nickName": _nickName,
        "_phone": _phone
      }
    }
    
    return {
      code: 200,
      data: userInfoRes
    }
  } catch (e) {
    return {
      code: 201,
      msg: "系统错误！"
    }
  }
};
